package com.alibaba.yinan.domain.resource.domain;

import com.alibaba.cola.exception.BizException;
import com.alibaba.yinan.domain.common.AggregateRoot;
import com.alibaba.yinan.domain.resource.Allocation;
import com.alibaba.yinan.domain.resource.ResourceStatus;
import com.alibaba.yinan.domain.resource.ResourceType;
import com.alibaba.yinan.domain.task.Task;

import java.time.Instant;

/**
 * @ClassName Resource
 * @Author mengke
 * @create 2025/8/17 15:53
 * @Description
 */
public abstract class BaseResource extends AggregateRoot {

    /**
     * 资源ID
     */
    protected String id;

    /**
     * 资源名称
     */
    protected String name;

    /**
     * 资源编号
     */
    protected String code;

    /**
     * 资源类型
     */
    protected ResourceType type;

    /**
     * 资源状态
     */
    protected ResourceStatus status;

    /**
     * 资源分配信息
     */
    protected Allocation allocation;

    /**
     * 是否可用
     */
    public boolean isAvailableFor(Task task) {
        return this.status.equals(ResourceStatus.IDLE) || this.status.equals(ResourceStatus.RESERVED);
    }

    public void allocate(Task task) {
        if (!isAvailableFor(task)) {
            throw new BizException("Resource not available");
        }
        this.allocation = new Allocation(task.getId(), Instant.now());
        this.status = ResourceStatus.ALLOCATED;
    }

    public void release() {
        this.allocation = null;
        this.status = ResourceStatus.IDLE;
    }
}
